package com.jz.digital.view;

import android.app.Activity;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.AbsoluteSizeSpan;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.jz.digital.R;
import com.jz.digital.base.EditInputCallback;
import com.jz.digital.listener.FocusChangeCallBack;
import com.jz.digital.listener.OnTextChangedListener;

/**
 * Copyright (c) 2019 深圳市爱都科技有限公司. All rights reserved.
 *
 * @Author: xyb
 * @CreateDate: 2019-12-26 12:21
 * @description
 */
public class ViewMePhoneLogin extends FrameLayout {
    /**
     * 中间的文字
     */
    private EditText mEtName;
    /**
     * 删除的图片
     */
    private ImageButton mIbDelete;
    /**
     * 选择城市
     */
    private TextView mTvCountryChoose;

    /**
     * 分隔线
     */
    private View mViewLine;

    private Drawable mBackground;
    private ColorStateList mTextColor;
    private ColorStateList mTextColorHint;
    private String mTextHint;
    private int mTextSizeHint;

    private int mDeleteSourceId;

    /**
     * 是否显示下拉
     */
    private boolean mIsShowDrop;

    /**
     * 监听文字辩护
     */
    private OnTextChangedListener mOnTextChangedListener;

    private FocusChangeCallBack mFocusChangeCallBack;

    private TextWatcher mTextWatcher;

    /**
     * 容器的view
     */
    private View container;

    //private String mCountry = CountryManager.DEFAULT_COUNTRY;

    // 是否自动展示和隐藏国家选择，只要手动设置过就不会自动变化了..
    private boolean mAutoShowCountryCode = true;

    /**
     * 获取名字编辑框的内容
     * @return
     */
    public String getPhone() {
        return mEtName.getText().toString();
    }

    /**
     * 获取验证码
     * @return
     */
    public String getCode(){
        return mTvCountryChoose.getText().toString();
    }

    public void setPhoneHint(String hint){
        mEtName.setHint(hint);
    }

    public void setText(String text){
        mEtName.setText(text);
        validText(text);
        if (mOnTextChangedListener!=null)mOnTextChangedListener.changed(text);
    }

    private void validText(String text){
        if (!TextUtils.isEmpty(text)){
            //隐藏清除输入框内容按钮
        //    mIbDelete.setVisibility(View.GONE);
            if(text.contains("@")){
                mTvCountryChoose.setVisibility(View.GONE);
                mViewLine.setVisibility(View.GONE);
            } else if(text.length() > 6){
                //前期账号只支持邮箱，手机的相关显示不再需要
                //mTvCountryChoose.setVisibility(View.VISIBLE);
                //mViewLine.setVisibility(View.VISIBLE);
            }else {
                mTvCountryChoose.setVisibility(View.GONE);
                mViewLine.setVisibility(View.GONE);
            }
        }else {
         //   mIbDelete.setVisibility(View.GONE);
            mTvCountryChoose.setVisibility(View.GONE);
            mViewLine.setVisibility(View.GONE);
        }
    }

    /**
     * 设置
     * @param enable
     */
    public void setEditTextEnable(boolean enable){
        mEtName.setEnabled(enable);
        mIbDelete.setVisibility(enable ? VISIBLE:GONE);
    }

    /**
     * 设置背景颜色
     * @param background
     */
    public void setmBackground(Drawable background){
        container.setBackground(background);
    }


    public void setCountryCode(String code) {
        mTvCountryChoose.setText("+" + code);
        mTvCountryChoose.setTag(code);
    }

    /**
     * 设置选择国家区号是否显示
     *
     * @param showCountryCode
     */
    public void setShowCountryCode(boolean showCountryCode) {
        mAutoShowCountryCode = false;
        mTvCountryChoose.setVisibility(showCountryCode ? VISIBLE : GONE);
    }

    /**
     * 设置名字编辑框内容
     *
     * @param text
     */
    public void setNameHint(CharSequence text) {
        mTextHint = text.toString();
        if (mTextSizeHint > 0) {
            // 新建一个可以添加属性的文本对象
            SpannableString ss = new SpannableString(mTextHint);
            // 新建一个属性对象,设置文字的大小
            AbsoluteSizeSpan ass = new AbsoluteSizeSpan(mTextSizeHint, true);
            // 附加属性到文本
            ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            // 设置hint
            mEtName.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
        } else {
            mEtName.setHint(mTextHint);
        }
    }

    /**
     * 文字变化后的监听
     *
     * @param listener
     */
    public void setOnTextChangedListener(OnTextChangedListener listener) {
        mOnTextChangedListener = listener;
    }

    public void setFocusChangeCallBack(FocusChangeCallBack mFocusChangeCallBack) {
        this.mFocusChangeCallBack = mFocusChangeCallBack;
    }

    public ViewMePhoneLogin(@NonNull Context context) {
        this(context,null);
    }

    public ViewMePhoneLogin(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public ViewMePhoneLogin(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initType(context,attrs);
        initView();
        initListener();
    }


    private void initType(Context context, AttributeSet attrs) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ViewPhone);
        mDeleteSourceId = a.getResourceId(R.styleable.ViewPhone_phoneDeleteSrc,0);
        mBackground = a.getDrawable(R.styleable.ViewPhone_phoneBackground);
        mTextColor = a.getColorStateList(R.styleable.ViewPhone_phoneTextColor);
        mTextColorHint = a.getColorStateList(R.styleable.ViewPhone_phoneTextColorHint);
        mTextHint = a.getString(R.styleable.ViewPhone_phoneTextHint);
        mTextSizeHint = a.getInteger(R.styleable.ViewPhone_phoneTextSizeHint, 13);
        mIsShowDrop = a.getBoolean(R.styleable.ViewPhone_phoneRightShow,false);
        a.recycle();
    }


    private void initListener() {
        mTvCountryChoose.setOnClickListener(v -> {
            if (getContext() instanceof Activity) {
                chooseCountry(mTvCountryChoose.getTag().toString());
            }
        });
        mIbDelete.setOnClickListener(v -> mEtName.setText(""));
        mIbDelete.setVisibility(GONE);
        //给editText增加获得焦点的响应
        mEtName.setOnFocusChangeListener(new OnFocusChangeListener(){
            @Override
            public void onFocusChange(View v, boolean hasFocus){
                if(mFocusChangeCallBack!=null){
                    mFocusChangeCallBack.onFocusChange(hasFocus);
                }
                if(hasFocus){
                    mIbDelete.setVisibility(VISIBLE);
//                    container.setBackgroundResource(R.drawable.shape_rectangle_line_black_bg_white_10_corner);
                }
                else{
                    mIbDelete.setVisibility(GONE);
//                    if(mBackground!=null){
//                        container.setBackground(mBackground);
//                    }else {
//                        container.setBackgroundResource(R.drawable.shape_rectangle_bg_white_10_corner);
//                    }
                }
            }
        });
        mEtName.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        mEtName.setTypeface(Typeface.DEFAULT);
    }

    protected void chooseCountry(String countryCode) {
//        CountryChooseActivity.startActivity((Activity) getContext(), countryCode);
    }

    private void initView() {
        View view = LayoutInflater.from(getContext())
                .inflate(R.layout.widget_me_phone, this, true);

        container = view.findViewById(R.id.container);
        mEtName = view.findViewById(R.id.me_name_et);
        mIbDelete = view.findViewById(R.id.me_ib_delete_name);
        mTvCountryChoose = view.findViewById(R.id.tv_country_choose);
        mViewLine = view.findViewById(R.id.view_line);


        if (mBackground != null)
//            container.setBackground(mBackground);
        if (mTextColor != null) {
            mEtName.setTextColor(mTextColor);
        }
        if (mBackground == null) {
//            ColorUtil.shapeSolid(container, 10, textFieldBackgroundColor());
        }

        // 提示文字
        if (TextUtils.isEmpty(mTextHint) && mEtName.getHint() != null) {
            mTextHint = mEtName.getHint().toString();
        }
        if (mTextColorHint == null) {
//            mTextColorHint = ColorStateList.valueOf(textFieldPlaceholderColor());
        }
        mEtName.setHintTextColor(mTextColorHint);
        setNameHint(mTextHint);
        if(mDeleteSourceId != 0){
            setDeleteImageResource(mDeleteSourceId);
        }

    }



    public void setDeleteImageResource(@DrawableRes int resId){
        mIbDelete.setImageResource(resId);
    }

    private void setNameHint(String text) {
        mTextHint = text;
        if (TextUtils.isEmpty(mTextHint)) return;
        if (mTextSizeHint > 0) {
            // 新建一个可以添加属性的文本对象
            SpannableString ss = new SpannableString(mTextHint);
            // 新建一个属性对象,设置文字的大小
            AbsoluteSizeSpan ass = new AbsoluteSizeSpan(mTextSizeHint, true);
            // 附加属性到文本
            ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            // 设置hint
            mEtName.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
        } else {
            mEtName.setHint(mTextHint);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (mTextWatcher == null) {
            mTextWatcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (mOnTextChangedListener != null) {
                        mOnTextChangedListener.changed(s.toString());
                    }
                    validText(s.toString());
                    if(s.length()==0){
                        mEtName.getPaint().setFakeBoldText(false);
                    }else{
                        mEtName.getPaint().setFakeBoldText(true);
                    }
                }
            };
        }
        mEtName.addTextChangedListener(mTextWatcher);
    }

    public void addFilter(InputFilter... filters){
        if (filters==null||filters.length==0)return;
        for(InputFilter filter:filters){
            if(filter instanceof AccountAndEmailInputFilter){
                ((AccountAndEmailInputFilter) filter).setEditInputCallback(new EditInputCallback() {
                    @Override
                    public void errorTip() {
//                        NormalToast.showToast(IdoApp.getAppContext().getString(R.string.key_3409));
                    }
                });
            }else if(filter instanceof AccountInputFilter){
                ((AccountInputFilter) filter).setEditInputCallback(new EditInputCallback() {
                    @Override
                    public void errorTip() {
//                        NormalToast.showToast(IdoApp.getAppContext().getString(R.string.key_2003));
                    }
                });
            }
        }
        mEtName.setFilters(filters);
    }

    @Override
    protected void onDetachedFromWindow() {
        mEtName.removeTextChangedListener(mTextWatcher);
        super.onDetachedFromWindow();
    }


}
